
import execjs
import requests

"""
1、运行前请检查 是否有 fanyi.js文件 在此文件得同级目录
2、pip install execjs   安装依赖文件
3、运行
"""




def get_sgin(wd):
    # 处理js流程
    with open('fanyi.js','r') as f:
        cty = execjs.compile(f.read())
    res = cty.call('e', wd)
    return res




def get_trans(wd):
    url = "https://fanyi.baidu.com/v2transapi?from=en&to=zh"
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36",
        # "cookie":"BAIDUID=D786FAFAB3DC1E8C84CACD59DFADAEEA:FG=1; expires=Tue, 07-Jun-22 10:07:29 GMT; max-age=31536000; path=/; domain=.baidu_libray.com; version=1; BAIDUID_BFESS=D786FAFAB3DC1E8C84CACD59DFADAEEA:FG=1; Path=/; Domain=baidu_libray.com; Expires=Tue, 07 Jun 2022 10:07:29 GMT; Max-Age=31536000; Secure; SameSite=None"
        "cookie":"BAIDUID_BFESS=D786FAFAB3DC1E8C84CACD59DFADAEEA:FG=1; "
    }
    data = {
    "from": "en",
    "to": "zh",
    "query": wd,
    "transtype": "realtime",
    "simple_means_flag": "3",
    "sign": get_sgin(wd),
    "token": "31ce6a8e545be3abb245d54f86989fed",
    "domain": "common"
    }


    return requests.post(url, headers=headers, data=data).json()

def start_trans(res_dict):
    data_list = res_dict['trans_result']['data']
    for data in data_list:
        dst = data['dst']  # 翻译结果
        src = data['src']  # 待翻译文本
        print('待翻译文本：{}， 翻译结果：{}'.format(src, dst))


if __name__ == '__main__':
    wd = input('请输入要翻译得英文文本：')
    res_json = get_trans(wd)
    start_trans(res_json)